package com.learn.flutter_learn_vi;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.util.Map;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.StandardMessageCodec;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {

	private Context mContext;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		mContext = this;
		messageChannelFunction();
		GeneratedPluginRegistrant.registerWith(this.getFlutterEngine());
		CrashReport.initCrashReport(getApplicationContext(), "b55ed7e724", false);
	}

	private BasicMessageChannel<Object> mMessageChannel;

	private void messageChannelFunction() {
		//消息接收监听
		//BasicMessageChannel （主要是传递字符串和一些半结构体的数据）
		//创建通
		mMessageChannel = new BasicMessageChannel<Object>(getFlutterEngine().getDartExecutor().getBinaryMessenger(), "flutter_and_native_100", StandardMessageCodec.INSTANCE);
		// 接收消息监听
		mMessageChannel.setMessageHandler(new BasicMessageChannel.MessageHandler<Object>() {
			@Override
			public void onMessage(Object o, BasicMessageChannel.Reply<Object> reply) {

				Map<Object, Object> arguments = (Map<Object, Object>) o;

				//方法名标识
				String lMethod = (String) arguments.get("method");

				if (lMethod.equals("doc")) {
					//测试通过Flutter打开Android Activity
					String filePath = (String) arguments.get("path");
					Intent intent = new Intent("android.intent.action.VIEW");
					intent.addCategory("android.intent.category.DEFAULT");
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					Uri uri;
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
						// "com.ansen.fileprovider.fileprovider"即是在清单文件中配置的authorities
						// 通过FileProvider创建一个content类型的Uri
						uri = FileProvider.getUriForFile(mContext, "com.broker.liming", new File(filePath));
						intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
					} else {
						uri = Uri.fromFile(new File(filePath));
					}
					intent.setDataAndType(uri, "application/msword");
					mContext.startActivity(intent);

				}
			}
		});

	}


}
